package com.sq.system.controller;

import com.sq.common.web.base.TableDataInfo;
import com.sq.common.web.domain.AjaxResult;
import com.sq.system.base.BaseController;
import com.sq.system.pojo.SysMenu;
import com.sq.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

import static com.sq.common.web.domain.AjaxResult.success;

/**
 * @Author Li sir
 * @Date 2024/10/14
 */
@RestController
@RequestMapping("/api/menu/")
public class SysMenuController  extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;


    @GetMapping("tree/{username}")
    public AjaxResult selectMenuTree(@PathVariable(name = "username",required = true) String username){
        List<SysMenu> sysMenuList =  sysMenuService.selectRoleMenuTreeByUsername(username);
        return success(sysMenuList);
    }

    @PostMapping("list")
    public TableDataInfo selectAllMenu(@RequestBody SysMenu sysMenu){

        startPage(sysMenu.getPageNum(),sysMenu.getPageSize());

        List<SysMenu> sysMenuList =  sysMenuService.selectAllMenu(sysMenu);

        return getDataTable(sysMenuList);
    }

    @GetMapping("getone/{menuId}")
    public AjaxResult getOne(@PathVariable("menuId") Long menuId){
        SysMenu sysMenu = sysMenuService.selectOneMenu(menuId);
        return AjaxResult.success(sysMenu);
    }


    @PostMapping("insert")
    public AjaxResult insertOrUpdate(@RequestBody SysMenu sysMenu){

        boolean off = false;

        if (Objects.isNull(sysMenu.getMenuId())){
            off = sysMenuService.saveSysMenu(sysMenu);
        }else {
            off = sysMenuService.updateMenuById(sysMenu);
        }

        if (off){
            return success();
        }

        return AjaxResult.error();
    }


    @GetMapping("delete/{menuId}")
    public AjaxResult deleteMenu(@PathVariable("menuId") Long menuId){
        boolean b = sysMenuService.delMenuById(menuId);
        return  b ? AjaxResult.success() : AjaxResult.error();
    }

}
